<template>
    <div class="class-table" v-if="weekCourse != ''">
			<view class="uni-header">
				<view class="uni-group">
					<el-select v-model="value" size="mini" placeholder="请选择" :loading="termLoading" @focus="searchOption">
							<el-option
								v-for="item in options"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				</view>
			</view>
        <div class="table-wrapper">
            <div class="tabel-container">
                <table>
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th v-for="(weekNum, weekIndex) in weeks" :key="weekIndex"> {{'周' + digital2Chinese(weekNum, 'week')}}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(courseNum, courseIndex) in coursesLen" :key="courseIndex">

                            <td>
                                <p>{{'第' + digital2Chinese(courseNum) + "节"}}</p>
                                <p class="period">{{ classTableData.period[courseIndex] }}</p>
                            </td>

                            <td class="gezi" v-for="(weekNum, weekIndex) in weeks" :key="weekIndex">
															<view class="optional"><optional :detail="fieldCharacter(weekIndex, courseIndex)"></optional></view>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>

<script>
const db = uniCloud.database();
const dbCmd = db.command;

import {
		mapState
	} from 'vuex'

const Optional = {
	functional: true,
	render(h,{props , parent}){
		let {detail} = props
		if(detail != ''){
		 	return detail.map((item)=>{
			 let {name, id, cycle, teacher, address , parent_id} = item
			 const model = {
				 value : parent.radio,
				 callback : v => parent.radio = v
			 }
			   return	<div>
					{`${name}`}<br/>{`(${id} ${teacher} ${cycle} ${address})`}
				 </div>
			})
		}
	}
}	
//
export default {
		components: { Optional },
    data() {
        return {
					credit: 0, //总学分
					usedcredit: 0 , //已用学分
					radio: '', //选项值
					weeks: [], //周集合
					coursesLen: 0, //最大课节数
					weekCourse: [], //课程集合
					termLoading: false, // 学期时间loading
					classTableData: { //mock模拟的数据
                period: [ '09:00-10:20', '10:40-12:00', '12:30-13:50', '14:00-15:20', '15:30-16:50', '17:00-18:20','19:00-20:20','20:30-21:50'], //时间段
          //       weekCourse: [
          //           {
          //               'week': 1,
          //               'courses': [
					//									course:[	
					//                        ]
          //               ]
          //           },
										// {
										//     'week': 2,
										//     'courses': [
										//     ]
										// }
            },
						options: [],
						value: ''
        }
    },
    async created() {
			await this.loadClass();
			await this.updateData();
			this.initWeekCourses();
    },
		
		computed: {
			...mapState('user', ['userInfo']),
		},
    methods: {
			
			/**
			 * 获取搜索项
			 */
			searchOption(){
				this.termLoading = true
				let {username} = this.userInfo
				this.$request('center/searchOption',{username}).then((res)=>{
					this.options = res
					this.termLoading = false
				})
			},
			
			// 查询新
			search(){
				
			},
			
			/**
			 * 点击退课
			 */
			async delClass(){
				uni.showLoading({
				  mask: true
				})
				console.log('start request')
				let class_id = this.radio
				let {username} = this.userInfo
				console.log(username , class_id)
				if(username && class_id){
					await this.$request('course/dropCourse',{username , class_id}).then(async (res)=>{
						uni.showToast({
						  title: res
						})
						await this.loadClass();
						await this.updateData();
						this.initWeekCourses();
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
				}
			},
			
			/**
			 * 更新数据，对数据进行排序
			 */
			updateData() {
					/* 将数据按从周日到周六排序 */
					this.weekCourse.sort((a, b) => {
							return a.week - b.week;
					});
					
					/* 将数据按从第一节到第n节排序 */
					for (let v of this.weekCourse) {
							for (let k in v) {
									if (k === 'courses') {
											v[k].sort((a, b) => {
													return a.index - b.index;
											});
									}
							}
					}
			},
			/**
			 * 计算周数据及课节数
			 */
			initWeekCourses() {
					const that = this;
					this.weeks = []; //周集合
					this.coursesLen = 8; //最大的课节数
					this.weeks = this.weekCourse.map((item, index) => {
							for (let k in item) {
									if (k === 'courses') {
											let maxCoursesLen = 0;
											/* 取出一周中最大的课节数及当天的最大课节数 */
											for (let j of item[k]) {
													j.index > that.coursesLen && (that.coursesLen = j.index); //取所有一周里最大课节值
													j.index > maxCoursesLen && (maxCoursesLen = parseInt(j.index)); //取当天最大课节值
											}
											/* 如果当天的课节总数小于当天的最大课节值 */
											if (item[k].length < maxCoursesLen) {
													for (let i = 0; i < maxCoursesLen; i++) { //以最大课节值为终点遍历当天课节
															if (!item[k][i] || item[k][i].index != (i + 1)) { //如果下标课节不存在或着与循环的下标不匹配
																	item[k].splice(i, 0, ''); //填充空课节
															}
													}
											}
									}
							}
							return item.week;
					});
			},
			
			/**
			 * 处理格子数据，无数据转换为字符串'-'
			 * @param {Number} weekIndex 周几对应的下标
			 * @param {Number} courseNum 第几节课对应的下标
			 * @returns {String} 返回对应的字符
			 */
			fieldCharacter(weekIndex, courseIndex) {
					if (
							this.weekCourse[weekIndex]
							&&
							this.weekCourse[weekIndex].courses[courseIndex]
							&&
							this.weekCourse[weekIndex].courses[courseIndex].index === courseIndex + 1 + ''
					) {
						
							return this.weekCourse[weekIndex].courses[courseIndex].course
							
					}
					return '';
			},


			/**
			* 数字转中文
			* @param {Number} num 需要转换的数字
			* @param {Boolean} identifier 标识符
			* @returns {String} 转换后的中文
			*/
			digital2Chinese(num, identifier) {
					const character = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
					return identifier === 'week' && (num === 0 || num === 7) ? '日' : character[num];
			},
			
			async loadClass(){
				let weekCourse = [{
					'week':1,'courses':[]},{
					'week':2,'courses':[]},{
					'week':3,'courses':[]},{
					'week':4,'courses':[]},{
					'week':5,'courses':[]}]
				
				
				return new Promise(async (resolve , reject)=>{
					db.collection('hr-userSchedule')
					.where({username:this.userInfo.username})
					.get().then((res)=>{
						if(res.result.affectedDocs!=0){
						let { credit , usedcredit , schedule = [] } = res.result.data[0]
						this.credit = credit
						this.usedcredit = usedcredit
						schedule.forEach((item)=>{
							weekCourse.some((key)=>{
								// 判断插入到周几
								if(item.day == key.week){
									// 判断插入到第几节课
									if(key.courses.length == 0){
										key.courses.push({
											index:item.node,
											course:[
												{
													"name":item.course_name,
													"id":item.class_id,
													"cycle":`${item.start_week}-${item.end_week}`,
													"teacher":item.nickname,
													"address":item.address[2],
													"parent_id":item.parent_id
												}]
										})
									} else {
										let change = key.courses.some((son)=>{
											// 判断插入到第几节课
											if(item.node == son.index){
												son.course.push({
													"name":item.course_name,
													"id":item.class_id,
													"cycle":`${item.start_week}-${item.end_week}`,
													"teacher":item.nickname,
													"address":item.address[2],
													"parent_id":item.parent_id
												})
												return true
											}else{
												return false
											}
										})
										if(!change){
											key.courses.push({
												index:item.node,
												course:[{
													"name":item.course_name,
													"id":item.class_id,
													"cycle":`${item.start_week}-${item.end_week}`,
													"teacher":item.nickname,
													"address":item.address[2],
													"parent_id":item.parent_id
												}]
											})
										}
									}
								}
							})
						})
						}
						this.weekCourse = weekCourse
						resolve()
					})
				})
			}
					
    }
};
</script>

<style lang="scss" scoped>
.class-table {
	.uni-header{
		flex-direction: row;
		justify-content: space-between;
	}
	.table-wrapper {
			width: 100%;
			height: 100%;
			overflow: auto;
	}
	.tabel-container {
		margin: 7px;

		table {
			table-layout: fixed;
			width: 100%;

			thead {
					background-color: #67a1ff;
					th {
							color: #fff;
							line-height: 17px;
							font-weight: normal;
					}
			}
			tbody {
					background-color: #eaf2ff;
					td {
							color: #677998;
							line-height: 24px;
					}
			}
			th,
			td {
					min-width: 10px;
					padding: 12px 2px;
					font-size: 12px;
					text-align: center;
			}
			tr td .optional{
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				align-items: center;
				.el-radio {
					width: 80%;
					padding: 0 5rpx;
					margin:5rpx 10rpx;
					.el-radio__label{
						width: 100%;
						text-overflow: ellipsis;
						white-space: normal;
						vertical-align: middle;
						display: inline-block;
						span {
							width: 80%;
							text-overflow: ellipsis;
							white-space: normal;
							vertical-align: middle;
							display: inline-block;
							font-size: 12px;
						}
					}
				}
				

			}
			tr td:first-child {
					color: #333;
					.period {
							font-size: 8rpx;
					}
			}
			
		}
	}
}
</style>
